package com.example.fms.controller;

import com.example.fms.constant.JwtClaimsConstant;
import com.example.fms.dto.resp.LoginRespDto;
import com.example.fms.dto.resp.RightRespDto;
import com.example.fms.dto.resp.RoleRightDTO;
import com.example.fms.dto.resp.UserRespDto;
import com.example.fms.entity.Role;
import com.example.fms.entity.User;
import com.example.fms.entity.UserRole;
import com.example.fms.properties.JwtProperties;
import com.example.fms.service.RoleService;
import com.example.fms.service.UserService;
import com.example.fms.utils.JwtUtil;
import com.example.fms.vo.ResponseBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("login")
public class LoginController {
    @Resource
    private UserService userService;
    @Resource
    private JwtProperties jwtProperties;
    @Resource
    RoleService roleService;
    @PostMapping()
    public ResponseBean<LoginRespDto> login(@RequestBody UserRespDto req) {
        LoginRespDto respDto = new LoginRespDto();
        User userDto = userService.login(req);
        UserRole rolesByUserId = roleService.getRolesByUserId(userDto.getId());
        Role role = roleService.selectById(rolesByUserId.getRoleId());
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, userDto.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        respDto.setId(userDto.getId());
        respDto.setToken(token);
        if (!Objects.isNull(rolesByUserId)){
            respDto.setRid(rolesByUserId.getRoleId());
        }
        respDto.setUsername(userDto.getUserName());
        respDto.setEmail(userDto.getEmail());
        respDto.setRoleName(role.getRoleName());

        return ResponseBean.successMeat(respDto);

    }

}
